// 权限控制
// 路由跳转权限控制
// 菜单权限控制
import router from '@/router'
import { getToken } from '@/utils/auth'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
const WHITE_LIST = ['/login', '/404']
import { asyncRoutes } from '@/router/asyncRoutes'

router.beforeEach(async(to, from, next) => {
  nprogress.start()
  // to到哪里去
  // from从哪里来
  const token = getToken()
  if (token) {
    // 有token
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 最合适的位置，满足以上三个条件 调用action函数
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/fetchUserInfo')
        // 拿到两份数据
        console.log(res)
        const menus = res.roles.menus
        console.log(menus)
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))
        console.log(filterRoutes)
        // 把动态路由添加到应用的路由系统里
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList', filterRoutes)
      }
    }
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done()
})
